package com.fps.web.interceptor;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fps.web.model.BaseUser;
import com.fps.web.model.BaseUserLog;
import com.fps.web.service.BaseUserLogService;
import com.fpswork.common.Constant;
import com.fpswork.util.DateUtils;




public class SessionInterceptor implements HandlerInterceptor {
	@Resource
	private BaseUserLogService userlogservice;
	//不需要验证session的url，放行
	@SuppressWarnings("serial")
	private final static Map<String,String> ALLOW_SESSION_URL =
		new HashMap<String,String>(){
			{put("/login.html","1L");}
			{put("/loginSubmit.html","1L");}
		};
		
	//不需要记录日志的url，放行
	@SuppressWarnings("serial")
	private final static Map<String,String> ALLOW_LOG_URL =
		new HashMap<String,String>(){
			{put("/login.html","1L");}
			{put("/loginSubmit.html","1L");}
		};

	
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String url = request.getServletPath();
		if( allowSessionUrl(url) == true){
			return true;
		}
		BaseUser user = (BaseUser) request.getSession().getAttribute(Constant.SESSION_USER_KEY);
		
		
		if(null != user && null != user.getId()  ){
			return true;	
		}else{
			BaseUserLog log = new BaseUserLog();
			log.setBrowser(request.getHeader("User-Agent"));
			log.setIp(request.getRemoteAddr());
			log.setOpttime(DateUtils.getServerDate(DateUtils.F_YYYY_MM_dd_HH_mm_ss));
			log.setAction(url);
			log.setResult("FAILURE");
			log.setUserid("Unknown");
			log.setRealname(log.getUserid());		
			userlogservice.addUserLog(log);
			PrintWriter out = response.getWriter();  
	        out.println("<html>");      
	        out.println("<script>");      
	        out.println("window.open ('"+request.getContextPath() + "/login.html','_top')");      
	        out.println("</script>");      
	        out.println("</html>");
			return false;
		}
	}
	

	
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}


	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		String url = request.getServletPath();
		//这些不需要验证session ，放行
		
		/**
		 * 特别说明: 为什么要加 /login/turnLogin
		 * 因为在action重定向后，不能在去session获取值，否则报异常：java.lang.IllegalStateException: Cannot create a session after the response has been committed
		 */
		if(true == allowLogUrl(url) ){
			BaseUser user = (BaseUser) request.getSession().getAttribute(Constant.SESSION_USER_KEY);
			BaseUserLog log = new BaseUserLog();
			log.setBrowser(request.getHeader("User-Agent"));
			log.setIp(request.getRemoteAddr());
			log.setOpttime(DateUtils.getServerDate(DateUtils.F_YYYY_MM_dd_HH_mm_ss));
			log.setAction(url);
			log.setResult("SUCCESS");
			log.setUserid("Unknown");
			if(null != user ){
				log.setUserid(user.getId());
				log.setRealname(user.getRealname());
			}
			if(null == log.getRealname()){
				log.setRealname(log.getUserid());
			}
			userlogservice.addUserLog(log);
		}
	}
	
	/**
	 * seession 放行
	 * @param url
	 * @return false 不放行，true放行
	 */
	private boolean allowSessionUrl(String url){
		if(null == url){
			return false;
		}
		if(url.startsWith("/m_")){//移动端放行
			return true;
		}
		if(url.startsWith("/openInterface")){//开放
			return true;
		}
		if(null != ALLOW_SESSION_URL.get(url) ){
			return true;
		}
		String url1L = url.split("/")[1];
		if(null != ALLOW_SESSION_URL.get(url1L) ){
			return true;
		}
		return false;
		
	}
	
	
	/**
	 * 记录日志
	 * @param url
	 * @return false不记录 ,true 记录
	 */
	private boolean allowLogUrl(String url){
		if(null == url){
			return false;
		}
	
		if(null != ALLOW_LOG_URL.get(url) ){
			return false;
		}
		String url1L = url.split("/")[1];
		if(null != ALLOW_LOG_URL.get(url1L) ){
			return false;
		}
		
		return true;
		
	}
	
}
